import time
import random
import string
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas as pd


# 定义函数，随机生成6位数字验证码
def generate_code():
    return ''.join(random.sample(string.digits, 6))


# 定义函数，发送邮件
def send_email(to_addr, code, content):
    # 定义发件人邮箱和密码
    from_addr = '435949837@qq.com'
    password = 'uowmvyzaisqrbhdg'

    # 定义收件人邮箱
    to_addrs = to_addr

    # 定义邮件内容
    msg = MIMEMultipart()
    msg['From'] = from_addr
    msg['To'] = to_addrs
    msg['Subject'] = '发工资条'
    msg_content = '您的发工资条验证码为：' + code + '，请妥善保管。\r' + content
    msg.attach(MIMEText(msg_content, 'plain', 'utf-8'))

    # 发送邮件
    try:
        smtp_obj = smtplib.SMTP_SSL('smtp.qq.com', 465)
        smtp_obj.login(from_addr, password)
        smtp_obj.sendmail(from_addr, to_addrs, msg.as_string())
        print(f'邮件发送成功至 {to_addr}')
    except smtplib.SMTPException as e:
        print(f'邮件发送失败至 {to_addr}: {e}')


# 定义函数，批量发工资条excel表格
def send_pay_sheet(excel_file):
    # 读取excel表格
    try:
        df = pd.read_excel(excel_file)
    except Exception as e:
        print(f'读取excel表格失败: {e}')
        return

    # 遍历每一行，发送邮件，邮件内容为excel表格中对应行数据
    for index, row in df.iterrows():
        to_addr = row['邮箱']
        code = generate_code()
        # 邮件内容为excel表格中对应行数据 姓名	邮箱	部门	职位	基本工资	奖金	扣除	总工资
        content = (f'姓名：{row["姓名"]}\n邮箱：{row["邮箱"]}\n部门：{row["部门"]}\n职位：{row["职位"]}\n'
                   f'基本工资：{row["基本工资"]}\n奖金：{row["奖金"]}\n扣除：{row["扣除"]}\n总工资：{row["总工资"]}')
        send_email(to_addr, code, content)
        time.sleep(1)  # 延时1秒，防止频繁发送邮件


# 调用函数，批量发工资条
if __name__ == '__main__':
    excel_file = '发工资条.xlsx'
    send_pay_sheet(excel_file)
